//
//  MBLiveMainController.m
//  LiveBroadcast
//
//  Created by Maybe on 2019/2/19.
//  Copyright © 2019 moonBroadcast. All rights reserved.
//

#import "MBLiveMainController.h"
#import "MBLiveViewerModel.h"
#import "MBLiveMainTopCommonView.h"
#import "MBCloseLiveModel.h"
#import "MBLiveFinshPopView.h"
#import <ViewDeck/ViewDeck.h>
#import "MBLiveMainBottomCommonView.h"
#import "MBLiveMainGetGiftView.h"
#import "MBLiveMainMoreCommonView.h"
#import "MBLiveMainSendRedPagePopView.h"
#import "MBLiveMainBeautySettingView.h"
#import "MBLiveMainSensitivewordController.h"
#import "MBLiveMainBlackListController.h"
#import "MBLiveMainRemoveAudienceController.h"
#import "MBLiveMainAdminController.h"
#import "MBShareManager.h"
#import "MBShareCommonModel.h"
#import "MBSystemFriendController.h"
#import "MBLiveInfoModel.h"
#import "MBLiveMessageTableView.h"
#import "MBLiveGiftAnimationView.h"
#import "LiveGiftShowCustom.h"
#import "MBUserDetailController.h"
#import "MBLiveRemoveAndBlackController.h"

static NSInteger const TimerInterval = 5.0;

@interface MBLiveMainController ()<TXLivePushListener,TXLiveRecordListener,TIMMessageListener,LiveGiftShowCustomDelegate,MBLiveRemoveAndBlackDelegate>
@property (nonatomic, strong) TXLivePush    *txLivePublisher;
@property (nonatomic, copy)   NSString      *pushUrl;
@property (nonatomic, assign) NSString      *liveViewerCount;
@property (nonatomic, strong) MBLiveViewerModel *liveViewerModel;
@property (nonatomic, strong) NSMutableArray *liveViewerDataArray;
@property (nonatomic, strong) NSTimer       *timer;
@property (nonatomic, strong) MBLiveMainTopCommonView *topCommonView;
@property (nonatomic, strong) MBCloseLiveModel *closeLiveModel;
@property (nonatomic, strong) MBLiveFinshPopView *finishView;
@property (nonatomic, strong) MBLiveMainBottomCommonView *bottomCommonView;
@property (nonatomic, strong) MBLiveMainMoreCommonView *moreCommonView;
@property (nonatomic, strong) MBLiveMainBeautySettingView *beautyView;
@property (nonatomic, strong) MBLiveGiftAnimationView *giftAnimationView;
@property (nonatomic ,weak) LiveGiftShowCustom * customGiftShow;

@end

@implementation MBLiveMainController {
    BOOL _appIsBackground;
    BOOL _appIsInActive;
    UIView * _preViewContainer; /*预览页面*/
    BOOL     _isPreviewing; /*是否在预览*/
    MBLiveMessageTableView *_msgListView; /*消息列表展示*/
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}
-(void)dealloc {
    [self.timer invalidate];
    self.timer = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    [self createCustomNav];
    [self initPusher];
    [self getLiveViewer];
    [self getLiveInfo];
    
    NSTimer *timer = [NSTimer timerWithTimeInterval:TimerInterval target:self selector:@selector(timerRepeat) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    self.timer = timer;
    [[TIMManager sharedInstance] addMessageListener:self];
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    AVAuthorizationStatus statusVideo = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (statusVideo == AVAuthorizationStatusDenied) {
        [MBProgressHUD showMessage:@"获取摄像头权限失败，请前往隐私-相机设置里面打开应用权限"];
        return;
    }
    AVAuthorizationStatus statusAudio = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (statusAudio == AVAuthorizationStatusDenied) {
        [MBProgressHUD showMessage:@"获取麦克风权限失败，请前往隐私-麦克风设置里面打开应用权限"];
        return ;
    }
}


#pragma mark - IM
-(void)onNewMessage:(NSArray *)msgs {
    MB_WeakSelf(self);
    for (TIMMessage *msg in msgs) {
        int elemCount = [msg elemCount];
        for (int i = 0; i < elemCount; i++) {
            TIMElem *elem = [msg getElem:i];
            if ([elem isKindOfClass:[TIMTextElem class]]) {
                TIMTextElem *textElem = (TIMTextElem *)elem;
                NSString *text = textElem.text;
                MBLog(@"群聊收到文本%@",text);
//                LiveRoomMsgModel *msgMode = [[LiveRoomMsgModel alloc] init];
//                msgMode.type = LiveRoomMsgModeTypeOther;
//                msgMode.time = [[NSDate date] timeIntervalSince1970];
////                msgMode.userName = userName;
//                msgMode.userMsg = text;
//                [_msgListView appendMsg:msgMode];
                NSDictionary* dict= (NSDictionary *)[text mj_JSONObject];
                if([dict.allKeys containsObject:@"type"]){
                    if ([dict[@"type"] isEqualToString:@"1"]) {/*礼物特效*/
                        NSString *userName = dict[@"name"];
                        NSInteger count = [dict[@"count"] integerValue];
                        NSString *giftPicture = dict[@"giftPicture"];
                        NSString *giftName = dict[@"giftName"];
                        NSString *head = dict[@"head"];
                        NSString *giftID = dict[@"id"];
                        [self showGiftBarrageViewWithGiftCount:count giftName:giftName giftURL:giftPicture userName:userName head:head giftID:giftID];
                        if ([dict[@"giftUrl"] isNotBlank]) {
                            NSString *giftURL = dict[@"giftUrl"];
                            CGFloat giftTime = [dict[@"giftTime"] doubleValue];
                            self.giftAnimationView.hidden = NO;
                            [self.giftAnimationView.giftImageView yy_setImageWithURL:[NSURL URLWithString:giftURL] placeholder:nil options:YYWebImageOptionShowNetworkActivity completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
                                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(giftTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                    weakself.giftAnimationView.hidden = YES;
                                 });
                            }];
                        }
                    }else if ([dict[@"type"] isEqualToString:@"2"]){/*红包*/
                        
                        
                    }else if ([dict[@"type"] isEqualToString:@"3"]){/*新用户进直播间*/
                        NSString *userName = dict[@"name"];
                        NSString *content = dict[@"content"];

                        MBLog(@"++++新用户%@ 进入直播间",userName);
                        LiveRoomMsgModel *msgMode = [[LiveRoomMsgModel alloc] init];
                        msgMode.type = LiveRoomMsgModeTypeOther;
                        msgMode.time = [[NSDate date] timeIntervalSince1970];
                        msgMode.userMsg = [NSString stringWithFormat:@"%@",content];
                        msgMode.userName = userName;
                        
                        [_msgListView appendMsg:msgMode];
                    }else if ([dict[@"type"] isEqualToString:@"4"]){ /*发送弹幕消息*/
                        NSString *content = dict[@"content"];
                        NSString *name = dict[@"name"];
                        if ([content isNotBlank]) {
                            LiveRoomMsgModel *msgMode = [[LiveRoomMsgModel alloc] init];
                            msgMode.type = LiveRoomMsgModeTypeOther;
                            msgMode.time = [[NSDate date] timeIntervalSince1970];
                            msgMode.userMsg = [NSString stringWithFormat:@"%@",content];
                            msgMode.userName = name;
                            [_msgListView appendMsg:msgMode];
                        }
                    }
                }
            }else if ([elem isKindOfClass:[TIMCustomElem class]]){
                TIMCustomElem *customElem=(TIMCustomElem*)elem;
                NSData* data=customElem.data;
                NSDictionary* dict= [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                if([dict.allKeys containsObject:@"type"]){
                    if ([dict[@"type"]  isEqualToString:@"1"]) {/*礼物特效*/
                        if ([dict[@"giftUrl"] isNotBlank]) {
                            NSString *giftURL = dict[@"giftUrl"];
                            CGFloat giftTime = [dict[@"giftTime"] doubleValue];
                            self.giftAnimationView.hidden = NO;
                            [self.giftAnimationView.giftImageView yy_setImageWithURL:[NSURL URLWithString:giftURL] placeholder:nil options:YYWebImageOptionShowNetworkActivity completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
                                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(giftTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                    weakself.giftAnimationView.hidden = YES;
                                });
                            }];
                        }
                        
                    }else if ([dict[@"type"] isEqualToString:@"2"]){/*红包*/
                        
                        
                    }else if ([dict[@"type"] isEqualToString:@"3"]){/*新用户进直播间*/
                        NSString *userName = dict[@"name"];
                        MBLog(@"++++新用户%@ 进入直播间",userName);
                        LiveRoomMsgModel *msgMode = [[LiveRoomMsgModel alloc] init];
                        msgMode.type = LiveRoomMsgModeTypeOther;
                        msgMode.time = [[NSDate date] timeIntervalSince1970];
                        msgMode.userMsg = [NSString stringWithFormat:@"%@%@",userName,@"来到直播间"];
                        [_msgListView appendMsg:msgMode];
                    }else if ([dict[@"type"] isEqualToString:@"4"]){ /*发送弹幕消息*/
                        NSString *content = dict[@"content"];
                        if ([content isNotBlank]) {
                            LiveRoomMsgModel *msgMode = [[LiveRoomMsgModel alloc] init];
                            msgMode.type = LiveRoomMsgModeTypeOther;
                            msgMode.time = [[NSDate date] timeIntervalSince1970];
                            msgMode.userMsg = content;
                            [_msgListView appendMsg:msgMode];
                        }
                    }
                }
            }
        }
    }
}

#pragma mark - 消息列表
- (void)appendSystemMsg:(NSString *)msg {
    LiveRoomMsgModel *msgMode = [[LiveRoomMsgModel alloc] init];
    msgMode.type = LiveRoomMsgModeTypeSystem;
    msgMode.userMsg = msg;
    [_msgListView appendMsg:msgMode];
}


/*获取观看人数*/
-(void)getLiveViewerCount {
    NSDictionary *param = @{
                            @"liveId":self.liveID,
                            @"userId":filter([MBUserModel sharedMBUserModel].userInfo.userId)
                            };
    MB_WeakSelf(self);
    [MBHttpRequset requestWithUrl:kLive_live_getLiveViewerCount setParams:param isShowProgressView:NO success:^(id  _Nonnull AJson) {
        weakself.liveViewerCount = [NSString stringWithFormat:@"%@",AJson];
    } failure:^(id  _Nonnull AJson) {
        
    }];
}
/*获取观众*/
-(void)getLiveViewer {
    NSDictionary *param = @{
                            @"liveId":self.liveID,
                            };
    MB_WeakSelf(self);
    [MBHttpRequset requestWithUrl:kLive_live_getLiveViewer setParams:param isShowProgressView:NO success:^(id  _Nonnull AJson) {
        weakself.liveViewerDataArray = [MBLiveViewerModel mj_objectArrayWithKeyValuesArray:AJson];
        weakself.topCommonView.audienceDataArray = weakself.liveViewerDataArray;
        
    } failure:^(id  _Nonnull AJson) {
        
    }];
}
/*获取直播详情*/
-(void)getLiveInfo {
    NSDictionary *param = @{
                            @"liveId":self.liveID,
                            @"userId":filter([MBUserModel sharedMBUserModel].userInfo.userId)
                            };
    MB_WeakSelf(self);
    [MBHttpRequset requestWithUrl:kLive_getLiveInfo setParams:param isShowProgressView:NO success:^(id  _Nonnull AJson) {
        MBLiveInfoModel *liveInfoModel = [MBLiveInfoModel mj_objectWithKeyValues:AJson];
        weakself.topCommonView.liveInfoModel = liveInfoModel;
    } failure:^(id  _Nonnull AJson) {
        
    }];
}

/*每5s 轮询获取观众*/
-(void)timerRepeat {
//    [self getLiveViewerCount];
    [self getLiveViewer];
    [self getLiveInfo];
}

#pragma mark - event

-(void)jumpToUserCenterVC:(NSString *)userID {
    MBUserDetailController *vc = [[MBUserDetailController alloc]init];
    vc.userId = userID;
    [self.navigationController pushViewController:vc animated:YES];
}

/*退出直播间*/
-(void)quitLiveRoom {
    NSDictionary *param = @{
                            @"liveId":self.liveID,
//                            @"liveId":[[NSUserDefaults standardUserDefaults]objectForKey:LocalLiveId],
                            @"liveUserId":filter([MBUserModel sharedMBUserModel].userInfo.userId)
                            };
    MB_WeakSelf(self);
    [MBHttpRequset requestWithUrl:kLive_live_close setParams:param isShowProgressView:NO success:^(id  _Nonnull AJson) {
        [weakself quitLiveRoomSendIMMessage:^(BOOL success) {
            if (success) {
                [[TIMGroupManager sharedInstance] deleteGroup:self.streamID succ:^{
                    [weakself quitOtherLiveRoom:AJson];
                    
                } fail:^(int code, NSString *msg) {
                    //            [self enterGroup];
                }];
            }
        }];
        
       
    } failure:^(id  _Nonnull AJson) {
        
    }];
}

/*退出直播间*/
-(void)quitOtherLiveRoom:(id)AJson {
    MB_WeakSelf(self);
    [self stopRtmp]; /*停止推流*/
    self.closeLiveModel = [MBCloseLiveModel mj_objectWithKeyValues:AJson];
    [[UIApplication sharedApplication].keyWindow addSubview:self.finishView];
    self.finishView.anchorCloseModel = self.closeLiveModel;
    self.finishView.gotoHomeMainVCBlock = ^{
        [weakself.finishView removeFromSuperview];
        weakself.finishView = nil;
        MBBaseTabbarController *tabVC = (MBBaseTabbarController *)weakself.viewDeckController.centerViewController;
        [weakself.navigationController popToRootViewControllerAnimated:NO];
        [tabVC updateCurrentIndex:0];
    };
}
/*主播退出直播发送一条IM消息*/
-(void)quitLiveRoomSendIMMessage:(void (^)(BOOL success))sendSuccess {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@"5" forKey:@"type"];
    NSString *message = [dict mj_JSONString];
    [self sendMessage:message success:^(BOOL success) {
        sendSuccess(success);
    }];
}

/**发送群聊消息 */
-(void)sendMessage:(id)message success:(void(^)(BOOL success))success {
    TIMConversation * grp_conversation = [[TIMManager sharedInstance] getConversation:TIM_GROUP receiver:[NSString stringWithFormat:@"%@",self.streamID]];
    TIMMessage * msg = [[TIMMessage alloc] init];
    
    if ([message isKindOfClass:[NSString class]]) {/*文本消息*/
        TIMTextElem * text_elem = [[TIMTextElem alloc] init];
        [text_elem setText:message];
        [msg addElem:text_elem];
    }else { /*礼物消息*/
        TIMCustomElem *custom_elem = [[TIMCustomElem alloc]init];
        [custom_elem setData:message];
        [msg addElem:custom_elem];
    }
    [grp_conversation sendMessage:msg succ:^(){
        NSLog(@"SendMsg Succ");
        success(YES);
    }fail:^(int code, NSString * err) {
        success(NO);
        NSLog(@"SendMsg Failed:%d->%@", code, err);
    }];
}

#pragma mark - MBLiveRemoveAndBlackDelegate
-(void)mbLiveRemoveAndBlackBlackAudience:(NSString *)audienceID {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@"7" forKey:@"type"];
    [dict setObject:audienceID forKey:@"id"];

    NSString *message = [dict mj_JSONString];
    [self sendMessage:message success:^(BOOL success) {
        
    }];
}

-(void)mbLiveRemoveAndBlackRemoveAudience:(NSString *)audienceID {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@"6" forKey:@"type"];
    [dict setObject:audienceID forKey:@"id"];
    NSString *message = [dict mj_JSONString];
    [self sendMessage:message success:^(BOOL success) {
        
    }];
}

/*调转摄像头*/
-(void)cameraClick {
    [_txLivePublisher switchCamera];
}
/*打开收到礼物*/
-(void)openGiftView {
    MBLiveMainGetGiftView *view = [[MBLiveMainGetGiftView alloc]init];
    view.liveID = self.liveID;
    view.frame = (CGRect){{0,0},{kScreenWidth,kScreenHeight}};
    [self.view addSubview:view];
    MB_WeakSelf(view);
    view.removeBlock = ^{
        [weakview removeFromSuperview];
//        view = nil;
    };
}
/*展开 更多页面*/
-(void)openMoreView {
    MBLiveMainMoreCommonView *view =   [MBLiveMainMoreCommonView nibView];
    view.frame = (CGRect){{0,0},{kScreenWidth,kScreenHeight}};
    view.backgroundColor = [UIColor clearColor];
    view.liveID = self.liveID;
    [self.view addSubview:view];
    MB_WeakSelf(view);
    MB_WeakSelf(self);
    view.cancelBlock = ^{
        [weakview removeFromSuperview];
    };
    view.redPacketBlock = ^{
        [weakview removeFromSuperview];
        [weakself showRedPacketView];
    };
    view.beautyBlock = ^{
        [weakview removeFromSuperview];
        [weakself showBeautyView];
    };
    view.settingBlock = ^{
        [weakview removeFromSuperview];
        [weakself showSettingView];
    };
    view.notificationBlock = ^{
        [weakview removeFromSuperview];
        [weakself liveNotificationFans];
    };
    view.shareBlock = ^{
        [weakview removeFromSuperview];
        [weakself liveShare];
    };
}
/*展开 发送红包*/
-(void)showRedPacketView {
    MBLiveMainSendRedPagePopView *view = [MBLiveMainSendRedPagePopView nibView];
    view.frame = (CGRect){{0,0},{kScreenWidth,kScreenHeight}};
    view.backgroundColor = [UIColor clearColor];
    view.liveID = self.liveID;
    [self.view addSubview:view];
    MB_WeakSelf(view);
    view.cancelBlock = ^{
        [weakview removeFromSuperview];
    };
}
/*展开 美颜设置*/
-(void)showBeautyView {
    MBLiveMainBeautySettingView *view = [MBLiveMainBeautySettingView nibView];
    view.frame = (CGRect){{0,kScreenHeight - kTabSafeBottomMargin - 150},{kScreenWidth,150}};
    [self.view addSubview:view];
    MB_WeakSelf(view);
    view.beautySetBlock = ^(float skinValue, float beautyValue) {
        [weakview removeFromSuperview];
        [_txLivePublisher setBeautyStyle:0 beautyLevel:beautyValue whitenessLevel:skinValue ruddinessLevel:5];
    };
}

/**
 展开 设置
 */
-(void)showSettingView {
    MB_WeakSelf(self);
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//    UIAlertAction *sensitiveWordAction = [UIAlertAction actionWithTitle:@"敏感词设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        MBLiveMainSensitivewordController *vc = [[MBLiveMainSensitivewordController alloc]init];
//        vc.liveID = weakself.liveID;
//        [weakself.navigationController pushViewController:vc animated:YES];
//    }];
//    UIAlertAction *managerAction = [UIAlertAction actionWithTitle:@"管理员设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        MBLiveMainAdminController *vc = [[MBLiveMainAdminController alloc]init];
//        vc.liveID = weakself.liveID;
//        [weakself.navigationController pushViewController:vc animated:YES];
//    }];
    UIAlertAction *removeAction = [UIAlertAction actionWithTitle:@"踢人记录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        MBLiveMainRemoveAudienceController *vc = [MBLiveMainRemoveAudienceController new];
        vc.liveID = weakself.liveID;
        [weakself.navigationController pushViewController:vc animated:YES];
    }];
    UIAlertAction *blackListAction = [UIAlertAction actionWithTitle:@"拉黑记录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        MBLiveMainBlackListController *vc = [MBLiveMainBlackListController new];
        vc.liveID = weakself.liveID;
        [weakself.navigationController pushViewController:vc animated:YES];
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
//    [alert addAction:sensitiveWordAction];
//    [alert addAction:managerAction];
    [alert addAction:removeAction];
    [alert addAction:blackListAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}
/*主播通知粉丝*/
-(void)liveNotificationFans {
    NSDictionary *param = @{
                            @"liveId":self.liveID,
                            @"userId":filter([MBUserModel sharedMBUserModel].userInfo.userId)
                            };
    MB_WeakSelf(self);
    [MBHttpRequset requestWithUrl:kLive_live_liveNotificationFansApi setParams:param isShowProgressView:NO success:^(id  _Nonnull AJson) {
        [MBProgressHUD showMessage:@"已成功通知粉丝"];
    } failure:^(id  _Nonnull AJson) {
        
    }];
}
/*分享*/
-(void)liveShare {
    [self sendShareInfoRequest];
}

-(void)sendShareInfoRequest {
    NSDictionary *param = @{
                            @"id":filter([MBUserModel sharedMBUserModel].userInfo.userId),
                            @"type":@(5)
                            };
    MB_WeakSelf(self);
    [MBHttpRequset requestWithUrl:kLive_live_CommonShareApi setParams:param isShowProgressView:NO success:^(id  _Nonnull AJson) {
        MBShareCommonModel *model = [MBShareCommonModel mj_objectWithKeyValues:AJson];
        [[MBShareManager shareMBShareManager] mb_initShareView];
        [MBShareManager shareMBShareManager].shareTitle = @"分享标题";
        [MBShareManager shareMBShareManager].shareSubTitle = @"分享副标题";
        [MBShareManager shareMBShareManager].shareURL = model.url;
        [MBShareManager shareMBShareManager].shareImage = @"chose";
        [MBShareManager shareMBShareManager].sharePlatformBlockHandler = ^(MBSharePlatformType type) {
            switch (type) {
                case MBSharePlatformTypeSystemFriend:{
                    [weakself showSystemFriend];
                }break;
            }
        };

    } failure:^(id  _Nonnull AJson) {
        
    }];
}

-(void)showSystemFriend {
    MBSystemFriendController *vc = [[MBSystemFriendController alloc]init];
    vc.liveID = self.liveID;
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)showGiftBarrageViewWithGiftCount:(NSInteger)count giftName:(NSString *)giftName giftURL:(NSString *)giftURL userName:(NSString *)userName head:(NSString *)head giftID:(NSString *)giftID{
    LiveUserModel *userModel = [[LiveUserModel alloc]init];
    userModel.name = userName;
    userModel.iconUrl = head;
    LiveGiftListModel *giftModel = [[LiveGiftListModel alloc]init];
    giftModel.type = giftID;
    giftModel.name = giftName;
    giftModel.picUrl = giftURL;
    giftModel.rewardMsg = @"";
    
    LiveGiftShowModel * model = [LiveGiftShowModel giftModel:giftModel userModel:userModel];
    model.toNumber = count;
    model.interval = 0.15;
    [self.customGiftShow animatedWithGiftModel:model];
}

/*****************************************推流相关*************************************************/
#pragma mark - 推流相关
/*推流基本设置*/
-(void)initPusher {
    _appIsInActive = NO;
    _appIsBackground = NO;
    TXLivePushConfig* config = [[TXLivePushConfig alloc] init];
    config.enablePureAudioPush = NO;
    config.videoEncodeGop = 5;
    config.videoResolution = 1;
    config.touchFocus = NO;
    
    _txLivePublisher = [[TXLivePush alloc] initWithConfig:config];
    _txLivePublisher.recordDelegate = self;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppDidEnterBackGround:) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAppWillTerminate:) name:UIApplicationWillTerminateNotification object:nil];
    
    //    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarOrientationChanged:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
    [self startRtmp];
}

/*开始推流*/
-(BOOL)startRtmp {
    NSString *RTMPurl = self.rtmpString;
    if (!([RTMPurl hasPrefix:@"rtmp://"])) {
        [MBProgressHUD showMessage:@"推流地址错误"];
        return NO;
    }
    //是否有摄像头权限
    AVAuthorizationStatus statusVideo = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (statusVideo == AVAuthorizationStatusDenied) {
        [MBProgressHUD showMessage:@"获取摄像头权限失败，请前往隐私-相机设置里面打开应用权限"];
        return NO;
    }
    
    //是否有麦克风权限
    AVAuthorizationStatus statusAudio = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (statusAudio == AVAuthorizationStatusDenied) {
        [MBProgressHUD showMessage:@"获取麦克风权限失败，请前往隐私-麦克风设置里面打开应用权限"];
        return NO;
    }
    if (_txLivePublisher != nil) {
        TXLivePushConfig *_config = _txLivePublisher.config;
        _config.pauseFps = 10;
        _config.pauseTime = 300;
        _config.pauseImg = [UIImage imageNamed:@"pause_publish.jpg"];
        [_txLivePublisher setConfig:_config];
        
        _txLivePublisher.delegate = self;
        if (!_isPreviewing) {
            [_txLivePublisher startPreview:_preViewContainer];
            _isPreviewing = YES;
//            [_txLivePublisher showVideoDebugLog:_log_switch];
            
        }
        if ([_txLivePublisher startPush:RTMPurl] != 0) {
            NSLog(@"推流器启动失败");
            return NO;
        }
    }
    
    self.pushUrl = RTMPurl;
    return YES;
}

/*停止推流*/
- (void)stopRtmp {
    self.pushUrl = @"";
    if (_txLivePublisher != nil) {
        _txLivePublisher.delegate = nil;
        [_txLivePublisher stopPreview];
        _isPreviewing = NO;
        [_txLivePublisher stopPush];
    }
}


/**
 推流事件通知
 */
- (void)onPushEvent:(int)EvtID withParam:(NSDictionary *)param {
    NSDictionary *dict = param;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if (EvtID == PUSH_ERR_NET_DISCONNECT || EvtID == PUSH_ERR_INVALID_ADDRESS) {
//            [self clickPublish:_btnPublish];
        } else if (EvtID == PUSH_WARNING_HW_ACCELERATION_FAIL) {
//            _txLivePublisher.config.enableHWAcceleration = false;
//            [_btnHardware setImage:[UIImage imageNamed:@"quick2"] forState:UIControlStateNormal];
        } else if (EvtID == PUSH_ERR_OPEN_CAMERA_FAIL) {
//            [self stopRtmp];
//            [_btnPublish setImage:[UIImage imageNamed:@"start"] forState:UIControlStateNormal];
//            _publish_switch = NO;
//            [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
//            [self toastTip:@"获取摄像头权限失败，请前往隐私-相机设置里面打开应用权限"];
        } else if (EvtID == PUSH_ERR_OPEN_MIC_FAIL) {
//            [self stopRtmp];
//            [_btnPublish setImage:[UIImage imageNamed:@"start"] forState:UIControlStateNormal];
//            _publish_switch = NO;
//            [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
//            [self toastTip:@"获取麦克风权限失败，请前往隐私-麦克风设置里面打开应用权限"];
        } else if (EvtID == PUSH_EVT_CONNECT_SUCC) {
//            [self getLiveViewerCount];
            [self getLiveViewer];
            [self getLiveInfo];
            MBLog(@"推流成功调用");
            BOOL isWifi = [AFNetworkReachabilityManager sharedManager].reachableViaWiFi;
            if (!isWifi) {
                __weak __typeof(self) weakSelf = self;
                [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
                    if (weakSelf.pushUrl.length == 0) {
                        return;
                    }
                    if (status == AFNetworkReachabilityStatusReachableViaWiFi) {
                        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@""
                                                                                       message:@"您要切换到WiFi再推流吗?"
                                                                                preferredStyle:UIAlertControllerStyleAlert];
                        [alert addAction:[UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
                            [alert dismissViewControllerAnimated:YES completion:nil];
                            //                            [weakSelf stopRtmp];
                            //                            [weakSelf startRtmp];
                            [weakSelf.txLivePublisher stopPush];
                            [weakSelf.txLivePublisher startPush:weakSelf.pushUrl];
                        }]];
                        [alert addAction:[UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action) {
                            [alert dismissViewControllerAnimated:YES completion:nil];
                        }]];
                        [weakSelf presentViewController:alert animated:YES completion:nil];
                    }
                }];
            }
        } else if (EvtID == PUSH_WARNING_NET_BUSY) {
//            [_notification displayNotificationWithMessage:@"您当前的网络环境不佳，请尽快更换网络保证正常直播" forDuration:5];
        }
        
        
        //NSLog(@"evt:%d,%@", EvtID, dict);
        long long time = [(NSNumber *) [dict valueForKey:EVT_TIME] longLongValue];
        //        int mil = (int) (time % 1000);
        //        NSDate *date = [NSDate dateWithTimeIntervalSince1970:time / 1000];
        //        NSString *Msg = (NSString *) [dict valueForKey:EVT_MSG];
    });
}

- (void)onNetStatus:(NSDictionary *)param {
    NSDictionary *dict = param;
    
    NSString *streamID = [dict valueForKey:STREAM_ID];
    if (![streamID isEqualToString:_pushUrl]) {
        return;
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        int netspeed = [(NSNumber *) [dict valueForKey:NET_STATUS_NET_SPEED] intValue];
        int vbitrate = [(NSNumber *) [dict valueForKey:NET_STATUS_VIDEO_BITRATE] intValue];
        int abitrate = [(NSNumber *) [dict valueForKey:NET_STATUS_AUDIO_BITRATE] intValue];
        int cachesize = [(NSNumber *) [dict valueForKey:NET_STATUS_CACHE_SIZE] intValue];
        int dropsize = [(NSNumber *) [dict valueForKey:NET_STATUS_DROP_SIZE] intValue];
        int jitter = [(NSNumber *) [dict valueForKey:NET_STATUS_NET_JITTER] intValue];
        int fps = [(NSNumber *) [dict valueForKey:NET_STATUS_VIDEO_FPS] intValue];
        int width = [(NSNumber *) [dict valueForKey:NET_STATUS_VIDEO_WIDTH] intValue];
        int height = [(NSNumber *) [dict valueForKey:NET_STATUS_VIDEO_HEIGHT] intValue];
        float cpu_usage = [(NSNumber *) [dict valueForKey:NET_STATUS_CPU_USAGE] floatValue];
        float cpu_usage_ = [(NSNumber *) [dict valueForKey:NET_STATUS_CPU_USAGE_D] floatValue];
        int codecCacheSize = [(NSNumber *) [dict valueForKey:NET_STATUS_CODEC_CACHE] intValue];
        int nCodecDropCnt = [(NSNumber *) [dict valueForKey:NET_STATUS_CODEC_DROP_CNT] intValue];
        NSString *serverIP = [dict valueForKey:NET_STATUS_SERVER_IP];
        int nSetVideoBitrate = [(NSNumber *) [dict valueForKey:NET_STATUS_SET_VIDEO_BITRATE] intValue];
        int videoGop = (int)([(NSNumber *) [dict valueForKey:NET_STATUS_VIDEO_GOP] doubleValue]+0.5f);
        NSString * audioInfo = [dict valueForKey:NET_STATUS_AUDIO_INFO];
        NSString *log = [NSString stringWithFormat:@"CPU:%.1f%%|%.1f%%\tRES:%d*%d\tSPD:%dkb/s\nJITT:%d\tFPS:%d\tGOP:%ds\tARA:%dkb/s\nQUE:%d|%d\tDRP:%d|%d\tVRA:%dkb/s\nSVR:%@\tAUDIO:%@",
                         cpu_usage_ * 100,
                         cpu_usage * 100,
                         width,
                         height,
                         netspeed,
                         jitter,
                         fps,
                         videoGop,
                         abitrate,
                         codecCacheSize,
                         cachesize,
                         nCodecDropCnt,
                         dropsize,
                         vbitrate,
                         serverIP,
                         audioInfo];
//        AppDemoLogOnlyFile(@"Current status, VideoBitrate:%d, AudioBitrate:%d, FPS:%d, RES:%d*%d, netspeed:%d", vbitrate, abitrate, fps, width, height, netspeed);
        
//        NSLog(@"mem %llu", get_app_consumed_memory_bytes());
    });
}

//static vm_size_t get_app_consumed_memory_bytes() {
//    struct task_basic_info info;
//    mach_msg_type_number_t size = sizeof(info);
//    kern_return_t kerr = task_info(mach_task_self(),
//                                   TASK_BASIC_INFO,
//                                   (task_info_t)&info,
//                                   &size);
//    if( kerr == KERN_SUCCESS ) {
//        return info.resident_size;
//    } else {
//        return 0;
//    }
//}

-(void)createUI {
    CGRect previewFrame = (CGRect){{0,0},{kScreenWidth,kScreenHeight}};
    _preViewContainer = [[UIView alloc] initWithFrame:previewFrame];
    [self.view insertSubview:_preViewContainer atIndex:0];
//    _preViewContainer.center = self.view.center;
    
    // 消息列表展示和输入
    _msgListView = [[MBLiveMessageTableView alloc] initWithFrame:CGRectMake(10, kScreenHeight/2, 300, kScreenHeight/4) style:UITableViewStyleGrouped];
    _msgListView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_msgListView];
    [self.view addSubview:self.giftAnimationView];

    [self.view addSubview:self.topCommonView];
    [self.view addSubview:self.bottomCommonView];
    //初始化礼物弹幕视图
    [self customGiftShow];
    MB_WeakSelf(self);
    self.topCommonView.quitBlock = ^{
        [weakself quitLiveRoom];
    };
    self.topCommonView.jumpBlock = ^(NSString * _Nonnull userID) {
        [weakself jumpToUserCenterVC:userID];
    };
    self.topCommonView.jumpRemoveAndBlackBlock = ^{
        MBLiveRemoveAndBlackController *vc = [[MBLiveRemoveAndBlackController alloc]init];
        vc.liveID = weakself.liveID;
        vc.delegate = weakself;
        [weakself.navigationController pushViewController:vc animated:YES];
    };
    self.bottomCommonView.cameraBlock = ^{
        [weakself cameraClick];
    };
    self.bottomCommonView.giftBlock = ^{
        [weakself openGiftView];
    };
    self.bottomCommonView.moreBlock = ^{
        [weakself openMoreView];
    };
    
}
-(void)createCustomNav {
    self.navigationItem.title = @"直播";
}

/*进入后台，暂停*/
- (void)onAppDidEnterBackGround:(NSNotification *)notification {
    [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        
    }];
    _appIsBackground = YES;
    [_txLivePublisher pausePush];
}

/*即将进入前台，暂停推流*/
- (void)onAppWillResignActive:(NSNotification *)notification {
    _appIsInActive = YES;
    [_txLivePublisher pausePush];
}

- (void)onAppDidBecomeActive:(NSNotification *)notification {
    _appIsInActive = NO;
    if (!_appIsBackground && !_appIsInActive)
        [_txLivePublisher resumePush];
}

- (void)onAppWillEnterForeground:(NSNotification *)notification {
    _appIsBackground = NO;
    if (!_appIsBackground && !_appIsInActive) [_txLivePublisher resumePush];
}

-(void)onAppWillTerminate:(NSNotification *)notification {
    [self quitLiveRoom];
}

/*美颜相关*/
#pragma mark - BeautyLoadPituDelegate
- (void)onLoadPituStart
{
}
- (void)onLoadPituProgress:(CGFloat)progress
{

}
- (void)onLoadPituFinished
{
  
}
- (void)onLoadPituFailed
{
}

/*美颜相关*/
#pragma mark - BeautySettingPanelDelegate
- (void)onSetBeautyStyle:(int)beautyStyle beautyLevel:(float)beautyLevel whitenessLevel:(float)whitenessLevel ruddinessLevel:(float)ruddinessLevel{
    [_txLivePublisher setBeautyStyle:beautyStyle beautyLevel:beautyLevel whitenessLevel:whitenessLevel ruddinessLevel:ruddinessLevel];
}

- (void)onSetEyeScaleLevel:(float)eyeScaleLevel {
    [_txLivePublisher setEyeScaleLevel:eyeScaleLevel];
}

- (void)onSetFaceScaleLevel:(float)faceScaleLevel {
    [_txLivePublisher setFaceScaleLevel:faceScaleLevel];
}

- (void)onSetFilter:(UIImage *)filterImage {
    [_txLivePublisher setFilter:filterImage];
}


- (void)onSetGreenScreenFile:(NSURL *)file {
    [_txLivePublisher setGreenScreenFile:file];
}

- (void)onSelectMotionTmpl:(NSString *)tmplName inDir:(NSString *)tmplDir {
    [_txLivePublisher selectMotionTmpl:tmplName inDir:tmplDir];
}

- (void)onSetFaceVLevel:(float)vLevel{
    [_txLivePublisher setFaceVLevel:vLevel];
}

- (void)onSetFaceShortLevel:(float)shortLevel{
    [_txLivePublisher setFaceShortLevel:shortLevel];
}

- (void)onSetNoseSlimLevel:(float)slimLevel{
    [_txLivePublisher setNoseSlimLevel:slimLevel];
}

- (void)onSetChinLevel:(float)chinLevel{
    [_txLivePublisher setChinLevel:chinLevel];
}

- (void)onSetMixLevel:(float)mixLevel{
    [_txLivePublisher setSpecialRatio:mixLevel / 10.0];
}

#pragma mark - getter and setter
-(NSMutableArray *)liveViewerDataArray {
    if (_liveViewerDataArray == nil) {
        _liveViewerDataArray = [NSMutableArray array];
    }
    return _liveViewerDataArray;
}
-(MBLiveMainTopCommonView *)topCommonView {
    if (_topCommonView == nil) {
        _topCommonView = [MBLiveMainTopCommonView nibView];
        _topCommonView.autoresizingMask = NO;
        _topCommonView.backgroundColor = [UIColor clearColor];
        _topCommonView.frame = (CGRect){{0,kNavStatusHeight},{kScreenWidth,60}};
    }
    return _topCommonView;
}
-(MBLiveFinshPopView *)finishView {
    if (_finishView == nil) {
        _finishView = [MBLiveFinshPopView nibView];
        _finishView.frame = (CGRect){{0,0},{kScreenWidth,kScreenHeight}};
        _finishView.currentPart = MBUserPartAnchor;
        _finishView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.8];
    }
    return _finishView;
}
-(MBLiveMainBottomCommonView *)bottomCommonView {
    if (_bottomCommonView == nil) {
        _bottomCommonView = [MBLiveMainBottomCommonView nibView];
        _bottomCommonView.backgroundColor = [UIColor clearColor];
        _bottomCommonView.frame = (CGRect){{0,kScreenHeight - kTabSafeBottomMargin - 100},{kScreenWidth,100}};
        _bottomCommonView.autoresizingMask = NO;
    }
    return _bottomCommonView;
}
-(MBLiveGiftAnimationView *)giftAnimationView {
    if (_giftAnimationView == nil) {
        _giftAnimationView = [[MBLiveGiftAnimationView alloc]initWithFrame:(CGRect){{0,0},{kScreenWidth,kScreenHeight}}];
        _giftAnimationView.autoresizingMask = NO;
        //        _giftAnimationView.frame = (CGRect){{0,0},{kScreenWidth,kScreenHeight}};
        _giftAnimationView.backgroundColor = [UIColor clearColor];
        _giftAnimationView.hidden = YES;
    }
    return _giftAnimationView;
}

- (LiveGiftShowCustom *)customGiftShow{
    if (!_customGiftShow) {
        _customGiftShow = [LiveGiftShowCustom addToView:self.view];
        _customGiftShow.addMode = LiveGiftAddModeAdd;
        [_customGiftShow setMaxGiftCount:3];
        [_customGiftShow setShowMode:LiveGiftShowModeFromTopToBottom];
        [_customGiftShow setAppearModel:LiveGiftAppearModeLeft];
        [_customGiftShow setHiddenModel:LiveGiftHiddenModeNone];
        [_customGiftShow enableInterfaceDebug:YES];
        _customGiftShow.delegate = self;
    }
    return _customGiftShow;
}

@end
